from flask import Blueprint, request, session
from werkzeug.security import generate_password_hash

from src.api.https import SUCCESS, fail_api, success_api
from src.model.UserModel import UserModel
from src.utils.check_require import login_required
from src.utils.user_tool import UserTool, USERNAME
from src.init.init_db import db
from src.utils.info_tool import getmessage

users_api = Blueprint('users_api', __name__, url_prefix='/api/users')

utool = UserTool()


@users_api.post('/register')
def register():
    # 注册
    # getmessage(request)
    # 提取所需信息
    username = request.json['username']
    name = request.json['name']
    password = request.json['password']
    print(f'username = {username}, password = {password}, name = {name}')
    message = utool.check(username, password, name)
    if message != SUCCESS:
        return fail_api(message)

    utool.init(username, password, name)
    print(f'success!!!')
    return success_api("用户注册成功")


@users_api.post('/login')
def login():
    # 登录
    if session.get('uid', False):
        session.pop('uid')
    #     print("已经存在")
    # print("uid不存在")
    # getmessage(request)

    username = request.json['username']
    password = request.json['password']
    user = utool.check_password(username, password, USERNAME)
    if isinstance(user, str):
        return fail_api(msg=user)

    session['uid'] = user.uid
    uid = user.uid
    name = user.name
    avatar = "http://" + request.host + "/" + user.avatar

    data = {"uid": uid, "role": user.role, "name": name, "avatar": avatar}
    return success_api(msg="用户登录成功", data=data)


@users_api.post('/logout')
@login_required
def logout():
    # 退出登录
    session.pop('uid')
    return success_api(msg="成功退出")


@users_api.post('/updateInfo')
@login_required
def update_info():
    # 更新用户信息
    getmessage(request)
    info = request.json
    info["avatar"] = None
    info.pop("avatar")
    print(f'info = {info}, type = {type(info)}')
    # print(f"type = {type(info['key3'])}")
    if utool.update(info, session['uid']):
        return success_api("成功")
    else:
        return fail_api("用户信息过期")


@users_api.post('/delete')
@login_required
def delete():
    uid = session.get('uid')
    print(f'uid = {uid}')
    session.pop('uid')

    user_to_delete = UserModel.query.filter_by(uid=uid).first()

    if user_to_delete is not None:
        db.session.delete(user_to_delete)
        db.session.commit()

        return success_api(msg="用户成功删除")
    else:
        return fail_api(msg="错误，未找到该用户")


@users_api.post('/userinfo')
@login_required
def get_user_info():
    # 查看用户详情
    uid = session.get('uid')
    info = utool.list(uid)
    if info is not None:
        return success_api(msg="用户信息查找成功", data=info)
    else:
        return fail_api("查找中出现错误")


@users_api.post('/updatePwd')
def updatePwd():
    # 更新用户密码
    # getmessage(request)
    username = request.json['username']
    oldPassword = request.json['oldPassword']
    newPassword = request.json['newPassword']
    repeatPassword = request.json['repeatPassword']

    if newPassword != repeatPassword:
        return fail_api(msg="两次密码不同")

    if oldPassword == newPassword:
        return fail_api(msg="新密码不能与旧密码相同")

    if len(newPassword) < 8:
        return fail_api(msg="密码不能小于8位")

    user = utool.check_password(username, oldPassword, USERNAME)
    if isinstance(user, str):
        return fail_api(msg=user)

    user.password = generate_password_hash(newPassword, salt_length=8)
    db.session.commit()

    return success_api(msg="密码更改成功")

@users_api.post('/userprofile')
@login_required
def get_user_profile():
    # 查看用户画像
    uid = session.get('uid')
    profile = utool.getProfile(uid)
    print(type(profile))
    if profile is not None:
        return success_api(msg="用户信息查找成功", data=profile)
    else:
        return fail_api("查找中出现错误")
